package edu.purdue.cs.ds.vss;

import java.io.Serializable;
import java.util.StringTokenizer;

/**
 * This represents the parent secret a share is generated from
 * @author ruchith
 *
 */
public class ParentIndex implements Serializable{
	
	/**
	 * For the compiler
	 */
	private static final long serialVersionUID = -7533282714759852375L;

	/**
	 * The secret index
	 */
	private int index;
	
	/**
	 * Server id
	 */
	private int server;
	
	/**
	 * Parent share data
	 */
	private ParentIndex parent;

	public ParentIndex(int server, int index, ParentIndex parent) {
		this.server = server;
		this.index = index;
		this.parent = parent;
	}
	
	public ParentIndex(String fromDisk) {
		StringTokenizer tok = new StringTokenizer(fromDisk, ";");
		int len = 0;
		
		String tmp = tok.nextToken(); //This is my info
		len = tmp.length();
		StringTokenizer tok2 = new StringTokenizer(tmp, ":");
		this.server = Integer.parseInt(tok2.nextToken());
		this.index = Integer.parseInt(tok2.nextToken());
		
		String next = tok.nextToken(); //Parent
		if(next.equals("ROOT")) {
			this.parent = null;
		} else {
			String substring = fromDisk.substring(len+1);
			this.parent = new ParentIndex(substring);
		}
			
	}
	

	public int getIndex() {
		return index;
	}

	public int getServer() {
		return server;
	}

	public ParentIndex getParent() {
		return parent;
	}
	
	@Override
	public String toString() {
		
		String val = "{" + parent + "} : server : " + this.server + " index : " + this.index;
		return val;
	}
	
	@Override
	public boolean equals(Object obj) {
		if(obj instanceof ParentIndex) {
			ParentIndex tmp = (ParentIndex) obj;
			return tmp.getIndex() == this.index && tmp.getServer() == this.server &&
				((this.parent == null && tmp.getParent() == null) ||
				this.parent.equals(tmp.getParent()));
		} else {
			return false;
		}
	}
	
	public String toDisk() {
		String val = "";
		val +=  this.server + ":" + this.index + ";";
		if(this.parent == null) {
			val += "ROOT";
		} else {
			val += parent.toDisk();
		}
		
		return val;
	}
	
}
